package socket;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Created by :Infaraway
 * DATE : 2017/3/4
 * Time : 0:03
 * Funtion : 测试socket通信基础
 */

/**
 * 1 ip和端口的具体意义
 * ip：网络中的一个主机地址
 * 端口：用于定为主机中一个网络程序
 *
 * InetAdress：对象表示网络中的一个地址
 *
 * TCP、IP编程
 * 服务器 / 客户端 :客户端发送请求到服务器，服务器接受请求并给予响应；
 * ServerSocket
 * Socket
 */

public class SocketTest {
    /**
     * InetAdress:表示互联网（局域网）一台主机的地址
     */
    @Test
    public void testInetAdress() throws UnknownHostException {

        InetAddress address = InetAddress.getByName("www.baidu.com");
        InetAddress addrLocal = InetAddress.getLocalHost();
        //输出 ：www.baidu.com/220.181.112.244
        System.out.println(address);
        System.out.println(addrLocal);
    }


    @Test
    public void SocketServerSocket() throws IOException {

        //创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(11111);
        //接受客户端的请求，并且得到socket对象
        Socket socket = serverSocket.accept();

        //输出 服务器和客户端进行交互
        OutputStream out = socket.getOutputStream();
        PrintWriter printWriter = new PrintWriter(out);

        printWriter.write("From : Server....");

        //关闭流
        printWriter.close();
        out.close();
        //关闭socket
        socket.close();
        serverSocket.close();
        System.out.println("Server is start...");
    }

    @Test
    public void SocketClientSocket() throws IOException {

        InetAddress address = InetAddress.getByName("127.0.0.1");
        //客户端创建Socket对象，并且同时向服务器端发出请求
        Socket socket = new Socket(address, 11111);

        //使用输入输出流进行数据交互
        InputStream in = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        System.out.println(br.readLine());

        br.close();
        in.close();
        socket.close();
    }

}
